package com.example.redis.util;

import cn.hutool.core.net.NetUtil;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @Author guoyb
 * @Date 2023/7/18  10:28
 */
@Component
@Slf4j
public class RedisCacheUtils<T> {

    @Resource
    private RedisTemplate<String, T> redisTemplate;

    /**
     * 获取存储的对象
     *
     * @param key key
     * @return 对象
     */
    public T getObject(String key) {
        if (StringUtil.isEmpty(key)) {
            return null;
        }
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 存入对象类型数据
     *
     * @param key   redis key
     * @param value redis value
     */
    public boolean setObject(String key, T value) {
        return setObject(key, value, 0);
    }

    /**
     * 存入对象类型数据，设置存储时间
     *
     * @param key   key
     * @param value value
     * @param time  存放时间
     */
    public boolean setObject(String key, T value, long time) {
        if (StringUtil.isEmpty(key) || value == null) {
            return false;
        }
        if (time == 0) {
            redisTemplate.opsForValue().set(key, value);
        } else {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        }
        return true;
    }

    public void redisLockTest() {
        String localhostStr = NetUtil.getLocalhostStr();
        String redisLock = "redisLock";

        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end ";
        DefaultRedisScript redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(luaScript);
        redisScript.setResultType(Boolean.class);
        redisTemplate.execute(redisScript, Arrays.asList(redisLock), localhostStr);
        log.info("============lua============");

    }
}
